import { STORAGE } from './types';

const PREFIXKEY = 'STORAGE_';

export const storageGet = <T extends object>(
	key: string,
	type: STORAGE = STORAGE.SESSION
): T | string => {
	const result = window[type].getItem(`${PREFIXKEY}${key}`);
	if (result) {
		try {
			return JSON.parse(result);
		} catch (error) {
			return result;
		}
	}
	return '';
};

export const storageSet = (
	key: string,
	value: any,
	type: STORAGE = STORAGE.SESSION
): void => {
	if (value instanceof Object) {
		value = JSON.stringify(value);
	}
	window[type].setItem(`${PREFIXKEY}${key}`, value);
};

export const storageDeleteKey = (
	key: string,
	type: STORAGE = STORAGE.SESSION
): void => {
	window[type].removeItem(`${PREFIXKEY}${key}`);
};
